import { compare } from "bcryptjs";
import { sign } from "jsonwebtoken";
import { serialize } from "cookie";
import { NextApiRequest, NextApiResponse } from "next";

// export async function POST(request: Request) {
//   const data = await request.json();
//   return Response.json({ receivedData: data }, { status: 201 });
// }

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  console.log("req: ", req);
  if (req.method !== "POST") return res.status(405).end();

  // 模拟数据库查询（实际应替换为真实数据库操作）
  const user = { id: 1, email: "user@example.com", password: "$2a$10$..." };

  if (req.body.email !== user.email) {
    return res.status(401).json({ error: "用户不存在" });
  }

  const isValid = await compare(req.body.password, user.password);
  if (!isValid) {
    return res.status(401).json({ error: "密码错误" });
  }

  const token = sign({ userId: user.id }, "123", {
    expiresIn: "1h",
  });
  res.setHeader(
    "Set-Cookie",
    serialize("auth", token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      maxAge: 3600,
      path: "/",
    })
  );

  return res.status(200).json({ success: true });
}
